/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate.model.dao;

import hibernate.pojo.Codesanpham;
import hibernate.util.HibernateUtil;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
 *
 * @author phathuynh
 */
public class CodeSanPhamDAO {
    //<editor-fold defaultstate="collapsed" desc="1. Mã hóa mã sp -> code sản phẩm">
    public static String MD5(String text){
        String encode = "";
        try{
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(text.getBytes());
            BigInteger dis = new BigInteger(1, md5.digest());
            encode = dis.toString(16);
        }catch(NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return encode;
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="2. Thêm codesp">
    public static int addProductCode(Codesanpham codesp){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tran = null;
        try{
            tran = session.beginTransaction();
            session.save(codesp);
            tran.commit();
        }catch(HibernateException hex){
            System.out.println(hex);
        }finally{
            session.close();
        }
        return 1;
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="2. Lấy mã đơn đặt hàng cuối cùng">
    public static int getLastOrderID(){
        int ddh = 0;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            String hql = "Select MAX(codesp.maCode) from Codesanpham codesp";
            Query query = session.createQuery(hql);
            Object objDdh = query.uniqueResult();
            ddh = (Integer)objDdh;
            ddh = ddh+1;
        }catch(HibernateException hex){
            System.err.print(hex);
        }finally{
            session.close();
        }
        return ddh;
    }
}
